<template>
  <el-form-item
    v-if="show"
    :label="label"
    :prop="fld.colname"
    :label-position="orientation"
    :required="fld.disporder > 0 && fld.nullable === 0"
    :class="['cx-fldform', { 'hl-text': type === 'hltext' }]"
  >
    <!-- 自定义标签插槽 -->
    <template #label>
      <slot name="label" :fld="fld">
        <span>{{ label }}</span>
      </slot>
    </template>

    <!-- 自定义值插槽 -->
    <slot name="value" :fld="fld">
      <!-- 文本输入框 -->
      <el-input
        v-if="textbox"
        v-model="internalFld.value"
        type="text"
        :size="size"
        :placeholder="placeholder"
        :readonly="readonly"
        :style="style"
      />

      <!-- 多行文本域 -->
      <el-input
        v-else-if="textarea"
        v-model="internalFld.value"
        type="textarea"
        :size="size"
        :placeholder="placeholder"
        :readonly="readonly"
        :rows="internalFld.disprows || 3"
        :style="style"
        :autosize="autoHeight"
        :show-word-limit="true"
      />

      <!-- 下拉选择框 -->
      <el-select
        v-else-if="select"
        v-model="normalizedValue"
        :size="size"
        :placeholder="placeholder"
        :disabled="readonly"
        :clearable="!readonly"
        :style="style"
        @change="onChangeSelect"
      >
        <el-option
          v-for="option in internalFld.options"
          :key="option.value"
          :value="option.value"
          :label="option.text"
        />
      </el-select>

      <!-- 可输入下拉框 -->
      <el-input
        v-else-if="dropdown"
        v-model="internalFld.value"
        class="input-with-select"
        clearable
        :size="size"
        :placeholder="placeholder"
        :readonly="readonly"
        :style="style"
        @input="onInputDropdown"
      >
        <template #append>
          <el-select
            v-model="internalFld.value"
            filterable
            :size="size"
            :placeholder="placeholder"
            :disabled="readonly"
          >
            <el-option
              v-for="(candidate, index) in internalFld.candidates"
              :key="index"
              :value="candidate"
              :label="candidate"
            />
          </el-select>
        </template>
      </el-input>

      <!-- 日期时间选择器组件 -->
      <DatePicker
        v-else-if="isDateTimeField"
        :fld="internalFld"
        :placeholder="placeholder"
        :readonly="readonly"
        :size="size"
        @change="handleDateChange"
      />
      
      <!-- 颜色选择器 -->
      <PickerColor
        v-else-if="colorPicker"
        v-model="internalFld.value"
        :label="fld.namec"
        :show-preview="true"
        @change="handleColorChange"
      />

      <!-- 单选按钮组 -->
      <el-radio-group
        v-else-if="radio"
        v-model="internalFld.value"
        :size="size"
        :disabled="readonly"
        :style="style"
      >
        <el-radio
          v-for="option in internalFld.options"
          :key="option.value"
          :label="option.value"
        >
          {{ option.text }}
        </el-radio>
      </el-radio-group>

      <!-- 多选复选框组 -->
      <el-select
        v-else-if="mulSel"
        v-model="internalFld.tmpVal"
        multiple
        :size="size"
        :placeholder="placeholder"
        :disabled="readonly"
        :style="style"
        @change="onChangeMulSel"
      >
        <el-option
          v-for="option in internalFld.options"
          :key="option.value"
          :value="option.value"
          :label="option.text"
        />
      </el-select>

      <!-- 值按钮 -->
      <el-input
        v-else-if="valbutton"
        v-model="internalFld.value"
        readonly
        :size="size"
        :style="style"
      >
        <template #append>
          <el-button v-if="enable && !readonly" icon="el-icon-search" @click="onValButton" />
        </template>
      </el-input>

      <!-- 开关控件 -->
      <el-switch
        v-else-if="switchFld"
        v-model="internalFld.value"
        :size="size"
        :disabled="readonly"
        :style="style"
        :inactive-value="fld.options[0].value"
        :active-value="fld.options[1].value"
      />

      <!-- 默认文本输入 -->
      <el-input
        v-else
        v-model="internalFld.value"
        type="text"
        :size="size"
        :placeholder="placeholder"
        :readonly="readonly"
        :style="style"
      />
    </slot>
  </el-form-item>
</template>

<script>
/**
 * 组件名称: Fld (Element UI 版本)
 * 功能说明: 属性字段组件，支持多种字段类型的渲染
 * 研发时间: 2025/11/17
 * 研发人员: AI Assistant
 * 
 * 基于 cx2-fld 改造为 Element UI 版本，适配桌面端
 */

import DatePicker from './DatePicker.vue'
import PickerColor from './PickerColor.vue'

export default {
  name: 'Fld',
  
  components: {
    DatePicker,
    PickerColor
  },

  props: {
    mode: { type: Number, default: 0 },
    fld: { type: Object, required: true },
    portrait: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    hint: { type: String, default: '' },
    size: { type: String, default: 'default' }
  },

  data() {
    return {
      internalFld: this.fld,
      dateFormat: 'YYYY-MM-DD',
      datetimeFormat: 'YYYY-MM-DD HH:mm:ss',
      dateFormatDb: 'YYYY-MM-DD',
      datetimeFormatDb: 'YYYY-MM-DD HH:mm:ss'
    }
  },

  computed: {
    /**
     * 计算字段组件的排列方向
     */
    orientation() {
      return this.mulSel || this.video || this.photoFile
        ? 'top'
        : this.portrait
        ? 'top'
        : 'right'
    },

    /**
     * 计算字段组件的样式
     */
    style() {
      return 'width: 100%;'
    },

    /**
     * 判断字段是否显示
     */
    show() {
      return this.fld.disporder > 0
    },

    /**
     * 计算字段的占位符文本
     */
    placeholder() {
      if (this.hint) {
        return this.hint
      }

      const prefix = this.select || this.dropdown ? '请选择' : '请填写'
      return prefix + this.fld.namec
    },

    /**
     * 是否为文本输入框类型
     */
    textbox() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_TEXTBOX
    },

    /**
     * 是否为文本域类型
     */
    textarea() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_RICHTEXT
    },

    /**
     * 是否为列表选择类型
     */
    select() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_LIST
    },

    /**
     * 是否为下拉框类型
     */
    dropdown() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_DROPDOWN
    },

    /**
     * 是否为单选框类型
     */
    radio() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_RADIO
    },

    /**
     * 是否为多选框类型
     */
    mulSel() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_MULTISEL
    },

    /**
     * 是否为值按钮类型
     */
    valbutton() {
      if (!cx || !cx.consts) return false
      return (
        this.fld.disptype === cx.consts.DISP_VALBUTTON ||
        this.fld.disptype === cx.consts.DISP_SELDYNA
      )
    },

    /**
     * 是否为开关切换类型
     */
    switchFld() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_SWITCH
    },

    /**
     * 是否为日期字段
     */
    isDateField() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_DATE
    },

    /**
     * 是否为年份字段
     */
    isYearField() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_DATEYEAR
    },

    /**
     * 是否为日期时间字段
     */
    isDateTimeField() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_TIMESTAMP
    },

    /**
     * 是否为时间字段
     */
    isTimeField() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_TIME
    },
    
    /**
     * 是否为颜色选择器
     */
    colorPicker() {
      if (!cx || !cx.consts) return false
      return this.fld.disptype === cx.consts.DISP_SELCOLOR
    },

    /**
     * 字段是否可编辑
     */
    enable() {
      return this.fld.editable
    },

    /**
     * 计算字段标签文本
     */
    label() {
      return this.fld.namec + ':'
    },

    /**
     * 计算字段是否为只读状态
     */
    readonly() {
      if (!cx || !cx.consts) return true
      return (
        this.mode === cx.consts.ATT_ADD || this.mode === cx.consts.ATT_EDIT
          ? !this.fld.editable
          : true
      )
    },

    /**
     * 计算文本域是否自动调整高度
     */
    autoHeight() {
      return this.fld.disprows === 1
    },

    /**
     * 字段类型名称
     */
    type() {
      if (!cx || !cx.fld) return 'textbox'
      return cx.fld.dispTypeName(this.fld.disptype, this.fld.disprows)
    },

    /**
     * 标准化下拉框的值
     */
    normalizedValue() {
      if (!this.select || !this.internalFld.options || this.internalFld.options.length === 0) {
        return this.internalFld.value
      }

      const matchingOption = this.internalFld.options.find(
        (option) =>
          option.value == this.internalFld.value ||
          String(option.value) == String(this.internalFld.value)
      )

      if (matchingOption) {
        return matchingOption.value
      }

      return this.internalFld.value
    }
  },

  watch: {
    'internalFld.value': function (newVal, oldVal) {
      this.$emit('fld-change', this.fld)
    },

    'internalFld.editable': function (newVal, oldVal) {
      this.$emit('rule-change', this.fld)
    },

    'internalFld.required': function (newVal, oldVal) {
      this.$emit('rule-change', this.fld)
    },

    'internalFld.disporder': function (newVal, oldVal) {
      this.$emit('rule-change', this.fld)
    }
  },

  created() {
    this.initializeFieldByType(this.internalFld)
  },

  methods: {
    /**
     * 根据字段类型进行初始化
     */
    async initializeFieldByType(fld) {
      const needQueryFldValue = [
        cx.consts.DISP_MULTISEL,
        cx.consts.DISP_DROPDOWN,
        cx.consts.DISP_RADIO,
        cx.consts.DISP_SWITCH,
        cx.consts.DISP_LIST
      ].includes(fld.disptype)

      let fldValue = null
      if (needQueryFldValue && cx.fldvalue) {
        fldValue = await cx.fldvalue.queryFldValueListAuto({
          tabname: fld.tabname,
          colname: fld.colname
        })
      }

      switch (fld.disptype) {
        case cx.consts.DISP_MULTISEL:
          this.initializeSelectList(fldValue)
          this.initializeMultiSelect(fld)
          break
        case cx.consts.DISP_DROPDOWN:
          this.initializeDropdown(fldValue)
          break
        case cx.consts.DISP_LIST:
        case cx.consts.DISP_SWITCH:
        case cx.consts.DISP_RADIO:
          this.initializeSelectList(fldValue)
          break
      }
    },

    /**
     * 初始化多选字段
     */
    initializeMultiSelect(fld) {
      fld.tmpVal = []
      if (fld.value != undefined && fld.value != null && fld.value != '') {
        fld.tmpVal = fld.value.split(',')
      }
    },

    /**
     * 初始化可输入的下拉框
     */
    initializeDropdown(fldValues) {
      this.internalFld.candidates = []
      fldValues?.forEach((optionItem) => {
        this.internalFld.candidates.push(optionItem.dbvalue)
      })
    },

    /**
     * 初始化下拉选择框
     */
    initializeSelectList(fldValues) {
      this.internalFld.options = []
      fldValues?.forEach((opt) => {
        this.internalFld.options.push({ text: opt.dispc, value: opt.dbvalue })
        opt.disable = !this.internalFld.editable
      })
    },

    /**
     * 处理日期变化
     */
    handleDateChange(value) {
      this.internalFld.value = value
    },

    /**
     * 处理多选
     */
    onChangeMulSel(val) {
      this.internalFld.value = this.internalFld.tmpVal.join(',')
    },

    /**
     * 处理可输入的下拉选择框
     */
    onInputDropdown(e) {
      this.internalFld.value = e
    },

    /**
     * 下拉选择框
     */
    onChangeSelect(e) {
      this.internalFld.value = e
    },

    /**
     * 处理自定义按钮
     */
    onValButton() {
      this.$emit('val-button', this.fld)
    },
    
    /**
     * 处理颜色变化
     */
    handleColorChange(color) {
      this.internalFld.value = color
    }
  }
}
</script>

<style lang="scss" scoped>
.input-with-select {
  width: 100%;
}

.cx-hl-text {
  font-weight: bold;
  color: #409eff;
}
</style>
